import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cupertino_date_picker/flutter_cupertino_date_picker.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/phoenix_footer.dart';
import 'package:flutter_easyrefresh/phoenix_header.dart';
import 'package:flutter_member/stytle/listview_overScrollbehavior.dart';
import 'package:flutter_member/utils/weekday.dart';
import 'package:flutter_member/widget/calendarshow/flutter_clean_calendar.dart';
import 'package:flutter_member/widget/custom_appbar.dart';
import 'package:flutter_member/widget/food_item_widget.dart';
import 'package:flutter_member/widget/loading_dialog.dart';
import 'package:flutter_member/widget/my_button.dart';
import 'package:flutter_member/widget/no_data.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:parse_server_sdk/parse_server_sdk.dart';

/// 膳食页面
class DietPage extends StatefulWidget {
  @override
  _DietPageState createState() => _DietPageState();
}

String MIN_DATETIME = '2019-05-17';
String MAX_DATETIME = '2020-12-31';
class _DietPageState extends State<DietPage> {
  //region 和日曆有關的
  DateTime _dateTime;
  bool _showTitle = true;
  String _format = 'yyyy-MMMM';
  DateTimePickerLocale _locale = DateTimePickerLocale.zh_cn;
  String dateTime = formatDate(DateTime.now(), [yyyy, '年', mm, '月']);
  final GlobalKey<CalendarState> calendarKey = GlobalKey();
  List _selectedEvents;
  DateTime _selectedDay = DateTime.now();
  int _day = DateTime.now().weekday;
  var findView = false;

  List<dynamic> listSelectFoods = [];

  //  日曆點擊事件
  void _handleNewDate(date) {
    setState(() {
      findView = false;
      _day = date.weekday;
//      _findDiet();
      _selectedDay = date;
      _selectedEvents = _events[_selectedDay] ?? [];
    });
    print(_selectedEvents);
  }

  //endregion

  var indexState = 0;

  //加餐組合
  List<Food> _addFoods = [];

  //選中的套餐ID
  Set _set = new Set();
  Map<String, String> _map = new Map();

  //加餐圖標
  var images = Image.asset(
    'images/add.png',
    height: 23,
    width: 23,
  );
  List<Payment> _list = [
    Payment('信用卡', false, 'images/xyk.png'),
    Payment('銀聯信用卡', false, 'images/yl.png'),
    Payment('澳門通錢包', false, 'images/amt.png'),
    Payment('支付寶', false, 'images/zfb.png'),
    Payment('微信支付', false, 'images/wxzf.png'),
    Payment('線下支付', false, 'images/xxzf.png')
  ];

  //顯示加餐
  bool _viewBool = false;

  //確認加餐狀態
  bool _addView = false;
  List<Food> _addSelectFoods = [];
  final Map _events = {};

  /// 每日套餐列表
  Map foodMap = {};
  //// 加載中
  bool _loading = true;
  //  彈窗選擇日期
  void _showDatePicker() {
    DatePicker.showDatePicker(
      context,
      pickerTheme: DateTimePickerTheme(
        backgroundColor: Color(0xfff9f9f9),
        showTitle: _showTitle,
        confirm: Text("完成",
            style: TextStyle(
                color: Color(0xff017afe),
                fontSize: 16,
                fontWeight: FontWeight.w500)),
        cancel: Text("取消", style: TextStyle(color: Colors.cyan)),
      ),
      minDateTime: DateTime.parse(MIN_DATETIME),
      maxDateTime: DateTime.parse(MAX_DATETIME),
      initialDateTime: _dateTime,
      dateFormat: _format,
      locale: _locale,
      onConfirm: (dateTime, List<int> index) {
        setState(() {
          _dateTime = dateTime;
          this.dateTime = formatDate(dateTime, [yyyy, '-', mm]);
          calendarKey.currentState.setToDate(dateTime, isWeek: false);
        });
      },
    );
  }

  //確認加餐
  _showModalBottomSheet(double width) {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      builder: (BuildContext context) {
        return Container(
          height: 300,
          color: Colors.amberAccent,
        );
      },
    ).then((val) {
      print(val);
    });
  }


  ///获得所有套餐
  Future<void> getFoodMenu({@required num weekday}) async {
    var queryMenu = QueryBuilder<ParseObject>(ParseObject("FoodMenu"))
      ..whereEqualTo("title", WeekDay.cnWeekDay(weekday))
      ..includeObject(['sections.foods', 'combos']);
    var repsoneFoodInfo = await queryMenu.query();
    if (repsoneFoodInfo.success && repsoneFoodInfo.results != null) {
      setState(() {
        foodMap.clear();
        _loading=false;
        repsoneFoodInfo.results.map((menu) {
          menu['sections'].map((sections) {
            foodMap.putIfAbsent(
                sections["title"],
                    () => sections['foods']
                    .map((foods) => {
                  "objectId": foods["objectId"],
                  "title": foods["title"],
                  "price": menu["price"],
                  "cover": foods.containsKey("cover") != false ? foods["cover"]["url"] : null
                })
                    .toList());
          }).toList();
        }).toList();
      });
    }else{
      setState(()=>_loading=false);
    }
  }



  //加餐
  Widget _buildRowAdd(int index, List<Food> foods, String mapKey) {
    return GestureDetector(
        onTap: () {
          setState(() {
            if (foods[index].blView != true) {
              foods[index].blView = true;
              _addSelectFoods.add(foods[index]);
            } else {
              foods[index].blView = false;
              _addSelectFoods.remove(foods[index]);
            }
          });
        },
        child: Stack(
          children: <Widget>[
            Column(
              children: <Widget>[
                Container(
                  height: ScreenUtil().setHeight(8),
                ),
                Card(
                  //z轴的高度，设置card的阴影
                  elevation: 3,
                  //设置shape，这里设置成了R角
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.all(Radius.circular(20.0)),
                  ),
                  //对Widget截取的行为，比如这里 Clip.antiAlias 指抗锯齿
                  clipBehavior: Clip.antiAlias,
                  semanticContainer: false,
                  child: Container(
                    width: ScreenUtil().setWidth(180),
                    height: ScreenUtil().setHeight(145),
                  ),
                ),
              ],
            ),
            Positioned(
              left: ScreenUtil().setWidth(15),
              right: ScreenUtil().setWidth(15),
              child: Container(
                  width: ScreenUtil().setWidth(180),
                  height: ScreenUtil().setHeight(159),
                  child: Column(
                    children: <Widget>[
                      Container(
                          width: ScreenUtil().setWidth(150),
                          height: ScreenUtil().setWidth(101),
                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(20),
                            child: foods[index].src != null
                                ? Image.network(
                              foods[index].src,
                              fit: BoxFit.fill,
                            )
                                : Image.asset(
                              'images/noimg.jpg',
                              fit: BoxFit.fill,
                            ), //沒有圖片顯示暫無圖片,
                          )),
                      Container(
                        height: ScreenUtil().setHeight(39),
                        width: ScreenUtil().setWidth(130),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: <Widget>[
                                Container(
                                    child: foods[index].blView
                                        ? Image.asset(
                                      'images/checkbox_us.png',
                                      width: ScreenUtil().setWidth(24),
                                      height: ScreenUtil().setHeight(22),
                                    )
                                        : Image.asset(
                                      'images/checkbox.png',
                                      width: ScreenUtil().setWidth(24),
                                      height: ScreenUtil().setHeight(22),
                                    )),
                                Container(
                                  margin: EdgeInsets.only(left: 10),
                                  child: Text(
                                    foods[index].title,
                                    textAlign: TextAlign.left,
                                    //超出範圍..顯示
                                    overflow: TextOverflow.ellipsis,
                                    style: TextStyle(
                                        fontWeight: FontWeight.bold,
                                        color: Color(0Xff154D7C),
                                        fontSize: ScreenUtil().setSp(14)),
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),
                      Container(
                        width: ScreenUtil().setWidth(150),
                        child: Text(
                          '\$ ${foods[index].price}',
                          textAlign: TextAlign.right,
                          style: TextStyle(
                              color: Color(0Xff93BB24),
                              fontSize: ScreenUtil().setSp(14)),
                        ),
                      )
                    ],
                  )),
            )
          ],
        ));
  }


  //初始化加餐數據
  void addSelectFoods() {
    _addFoods.first.blView = true;
    _addSelectFoods.add(_addFoods.first);
  }

  //清除加餐數據
  void clearSelectFoods() {
    for (var v in _addFoods) {
      v.blView = false;
    }
    _addSelectFoods.clear();
  }

  //計算加餐的總價
  double getTotalPrice() {
    var sum = 0.0;
    for (int i = 0; i < _addSelectFoods.length; i++) {
      sum = sum + _addSelectFoods[i].price;
      print(_addSelectFoods[i].price);
    }
    return sum;
  }

  @override
  void initState() {
    super.initState();
    getFoodMenu(weekday: DateTime.now().weekday);
  }

  @override
  Widget build(BuildContext context) {
    //獲得屏幕的寬度
    final width = MediaQuery.of(context).size.width;
    return CustomAppBar(
      title: "膳食",
      hight: 80,
      lowerColor: 0xffc5d6eb,
      upperColor: 0xff2d7ec6,
      body: Container(
        child: Column(
          children: <Widget>[
            _calendarWidget(),
            Expanded(
              child: Column(
                children:_bodyList(),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 主體集合
  List<Widget> _bodyList({width}) {
    List<Widget> list = [];
    /// 添加 日曆組件
    if(_loading==true){
      list.add(CLoadingDialog(text:"加載中"));
    }else{
      if (foodMap.length != 0) {
        list.add(
          Expanded(
            child: ScrollConfiguration(
                behavior: OverScrollBehavior(),
                child: EasyRefresh(
                  header: PhoenixHeader(),
                  footer: PhoenixFooter(),
                  child: SingleChildScrollView(
                    child: Column(
                      children:
                      foodMap != null ? _listFoodItemWidget() : Text("1111"),
                    ),
                  ),
                )),
          ),
        );
      }else{
        list.add(NoDataWidget());
      }
    }
    if( listSelectFoods.length!=0){
      list.add(
          _addMealWidget(
            width: width,
            onTap: () {
              setState(() {
                _viewBool = !_viewBool;
                _viewBool
                    ? images = Image.asset(
                  'images/add_us.png',
                  width: ScreenUtil().setWidth(32),
                  height: ScreenUtil().setHeight(32),
                )
                    : images = Image.asset(
                  'images/add.png',
                  width: ScreenUtil().setWidth(32),
                  height: ScreenUtil().setHeight(32),
                );
              });
            },
          )
      );
    }
    return list;
  }

  /// 加餐顯示組件
  Widget _addMealWidget({VoidCallback onTap, num width}) {
    return Container(
      padding: EdgeInsets.only(left: 20),
      child: Column(
        children: [
          InkWell(
            onTap: onTap,
            child: Row(
              children: [
                Image.asset(
                  'images/add.png',
                  width: ScreenUtil().setWidth(32),
                  height: ScreenUtil().setHeight(32),
                )
              ],
            ),
          ),
          _viewBool
              ? Container(
              padding: EdgeInsets.only(left: 20),
              child: Column(
                children: <Widget>[
                  Container(
                      height: ScreenUtil().setHeight(180), //
                      child: ScrollConfiguration(
                        behavior: OverScrollBehavior(),
                        child: ListView.separated(
                          padding: EdgeInsets.all(5),
                          scrollDirection: Axis.horizontal,
                          itemBuilder:
                              (BuildContext context, int foodIndex) =>
                              _buildRowAdd(foodIndex, _addFoods, '加餐'),
                          separatorBuilder:
                              (BuildContext context, int index) =>
                              Divider(),
                          itemCount: _addFoods.length,
                        ),
                      )),
                ],
              ))
              : Container(),
          Container(
            margin: EdgeInsets.only(top: 10, bottom: 10),
            child: Text(
              '* 以上餐單可能會因當日實際情況而有所改變，圖片僅供參考',
              style: TextStyle(
                  color: Color(0xff868686),
                  fontWeight: FontWeight.bold,
                  fontSize: ScreenUtil().setSp(12)),
            ),
          ),
          MyButton(onPressed: () => _showModalBottomSheet(width), title: "確 認")
        ],
      ),
    );
  }

  /// 日历选中

  Widget _calendarWidget() {
    return Container(
      decoration: new BoxDecoration(boxShadow: [
        BoxShadow(
          offset: Offset(0.0, 16.0),
          color: Color(0xfffefeff),
          blurRadius: 25.0,
          spreadRadius: -9.0,
        ),
      ]),
      child: Container(
          width: ScreenUtil().setWidth(370),
          padding: EdgeInsets.only(
            left: 20,
            right: 20,
          ),
          margin: const EdgeInsets.only(
            left: 15,
            right: 15,
          ),
          decoration: BoxDecoration(color: Colors.white, boxShadow: [
            BoxShadow(
              offset: Offset(0.0, 16.0),
              color: Color(0xfffefeff),
              blurRadius: 25.0,
              spreadRadius: -9.0,
            ),
          ]),
          child: Column(
            children: <Widget>[
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  RichText(
                    text: TextSpan(
                      children: [
                        TextSpan(
                          text: dateTime,
                          style: TextStyle(
                              color: Color(0xff144d7c),
                              fontWeight: FontWeight.w600,
                              fontSize: 20),
                        ),
                      ],
                    ),
                  ),
                  IconButton(
                    icon: Icon(Icons.keyboard_arrow_down),
                    color: Color(0xff144d7c),
                    onPressed: _showDatePicker,
                  )
                ],
              ),
              Calendar(
                key: calendarKey,
                events: _events,
                isDisableSwipeUpAndDow: false,
                isExpanded: false,
                onRangeSelected: (range) {
                  print("${range.from}, ${range.to}");
                  setState(() {
                    dateTime = formatDate(range.from, [yyyy, '年', mm, '月']);
//                        _handleNewDate(date);
                  });
                },
//                        onDateSelected: (date) => _handleNewDate(date),
                onDateSelected: (date) => getFoodMenu(weekday: date.weekday),
                isExpandable: true,
                showTodayIcon: true,
              ),
            ],
          )),
    );
  }

  /// 膳食标题
  Widget _mealTitle({@required String title}) {
    return Container(
        alignment: Alignment.centerLeft,
        margin: EdgeInsets.only(left: 20, top: 5, bottom: 5),
        child: Text(title,
            style: TextStyle(
                color: Color(0xff93BB24),
                fontSize: ScreenUtil().setSp(18))));
  }

  ///遍历 map 食物集合
  List<Widget> _listFoodItemWidget() {
    List<Widget> listWidget = [];
    foodMap.forEach((key, value) {
      listWidget.add(_mealTitle(title: key));
      List<Widget> listWidgets = [];
      value.map((food){
        listWidgets.add(
            FoodItemWidget(
              objectId: food["objectId"],
              title: food["title"],
              price: food['price'].toString(),
              image: food['cover'],
              onChange: (v) {
                setState(() {
                  if (v.length == 0) {
                    listSelectFoods.remove(food["objectId"]);
                    print(listSelectFoods);
                  } else {
                    listSelectFoods.add(v[0]);
                    print(listSelectFoods);
                  }
                });
              },
            )
        );
      }).toList();

      listWidget.add(Container(
        margin: EdgeInsets.only(left: 20),
        height: ScreenUtil().setHeight(160),
        child: ListView(
          scrollDirection: Axis.horizontal,
          children: listWidgets,
        ),
      ));
    });
    return listWidget;
  }
}
class FoodCombo {
  final String objectId;
  final String title; //星期幾
  final List<FoodType> foodType;

  FoodCombo(this.objectId, this.title, this.foodType);
}

class FoodType {
  final String title; //食物分類
  final List<Food> foods;

  FoodType(this.title, this.foods);
}

class Food {
  final String objectId;
  final String title;
  final String src;
  final int kcal; //千卡
  final int carbohydrate; //碳水化合物
  final int protein; //蛋白質
  final int fat; //脂肪
  final double price;
  bool blView = false;

  Food(this.objectId, this.title, this.src, this.kcal, this.carbohydrate,
      this.protein, this.fat, this.price);
}

class Payment {
  final String title;
  final String src;
  bool bl;

  Payment(this.title, this.bl, this.src);
}
